package com.qulai.amazon_us.service.basic.impl;

import com.google.gson.JsonArray;
import com.qulai.amazon_us.domain.basic.Image;
import com.qulai.amazon_us.domain.basic.Product;
import com.qulai.amazon_us.domain.basic.dto.ImageDto;
import com.qulai.amazon_us.mapper.basic.ImageMapper;
import com.qulai.amazon_us.mapper.basic.ProductMapper;
import com.qulai.amazon_us.service.basic.IImageService;
import com.qulai.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
/**
 * 商品图片Service业务层处理
 *
 * @author hunan
 * @date 2025-01-08
 */
@Service
public class ImageServiceImpl implements IImageService {
    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ProductMapper productMapper;

    private  final Gson gson = new Gson();

    /**
     * 查询商品图片
     *
     * @param id 商品图片主键
     * @return 商品图片
     */
    @Override
    public Image selectImageById(Long id) {
        return imageMapper.selectImageById(id);
    }

    @Override
    public Image selectImageByBasicId(Long basicId) {
        return imageMapper.selectImageByBasicId(basicId);
    }

    /**
     * 查询商品图片列表
     *
     * @param image 商品图片
     * @return 商品图片
     */
    @Override
    public List<Image> selectImageList(ImageDto image) {
        return imageMapper.selectImageList(image);
    }

    /**
     * 新增商品图片
     *
     * @param image 商品图片
     * @return 结果
     */
    @Override
    public int insertImage(Image image) {
        return imageMapper.insertImage(image);
    }

    /**
     * 修改商品图片
     *
     * @param image 商品图片
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateImage(Image image) {

        image.setUpdateTime(DateUtils.getNowDate());

        List<String> imgList = new ArrayList<>();

        imgList.add(image.getMainImage());
        imgList.add(image.getOtherImageUrl1());
        imgList.add(image.getOtherImageUrl2());
        imgList.add(image.getOtherImageUrl3());
        imgList.add(image.getOtherImageUrl4());
        imgList.add(image.getOtherImageUrl5());
        imgList.add(image.getOtherImageUrl6());
        imgList.add(image.getOtherImageUrl7());
        imgList.add(image.getOtherImageUrl8());
        imgList.add(image.getOtherImageUrl9());
        imgList.add(image.getOtherImageUrl10());
        imgList.add(image.getOtherImageUrl11());
        imgList.add(image.getOtherImageUrl12());
        imgList.add(image.getOtherImageUrl13());
        imgList.add(image.getOtherImageUrl14());
        imgList.add(image.getOtherImageUrl15());

        // 过滤空值
        imgList = imgList.stream()
                .filter(url -> url != null && !url.isEmpty() && !url.trim().equals(""))
                .collect(Collectors.toList());

        // 处理 OCR 结果
        if (imgList.size() >= 2 && image.getOcrStatus() <4){
            if (image.getOcrResult() != null && !image.getOcrResult().isEmpty() &&  image.getOcrResult().startsWith("{") ){

                try {

                    JsonObject ocrJson = gson.fromJson(image.getOcrResult(), JsonObject.class);
                    if (ocrJson.has("inch_url")) {
                        String inchUrl = ocrJson.getAsJsonArray("inch_url").get(0).getAsString();

                        if (imgList.contains(inchUrl)) {
                            int originalIndex = imgList.indexOf(inchUrl);

                            // 如果不在第二位，则交换位置
                            if (originalIndex != 1) {
                                // 保存原来的第二个元素
                                String secondItem = imgList.get(1);

                                // 将 inchUrl 移到第二位
                                imgList.set(1, inchUrl);

                                // 将原来的第二个元素移动到 inchUrl 原来的位置
                                imgList.set(originalIndex, secondItem);


                            }
                        }


                    }
                }catch (Exception e) {
                        // 处理 JSON 解析错误
                        System.err.println("解析 OCR 结果失败: " + e.getMessage());
                }
            }
        }

        //查询product商品的json_text,更新json_text


        Product db_p = productMapper.selectProductById(image.getBasicId().toString());

        JsonObject jsonTextObj = gson.fromJson(db_p.getJsonText(), JsonObject.class);

        if (jsonTextObj != null && jsonTextObj.size()>0) {

            // 更新 images_list
            JsonArray imgArray = new JsonArray();
            for (String img : imgList) {
                imgArray.add(img);
            }

            jsonTextObj.add("images_list",imgArray);
            jsonTextObj.addProperty("main_image", image.getMainImage());
        }

        String jsonText = new Gson().toJson(jsonTextObj);

        Product p = new Product();
        p.setId(image.getBasicId().toString());
        p.setStatus(image.getStatus());
        p.setMainImage(image.getMainImage());
        p.setJsonText(jsonText);
        p.setImageCount(imgList.size());
        p.setUpdateTime(DateUtils.getNowDate());
        p.setPublished(image.getPublished());

        int updateBasic = 0;
        int updateImage = 0;

        try {
            // 执行第一个更新
            productMapper.updateProduct(p);


            // 执行第二个更新
            imageMapper.updateImage(image);
        } catch (Exception e) {
            // 手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }


//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("basic_id", image.getBasicId());
//            params.put("status", image.getStatus());
//
//            if(updateBasic >0 && updateImage >0){
//                HttpUtils.sendPostToPython_v2(flush_basic_sync_image_prod, params);
//                return 1;
//            }
//
//        } catch (Exception e) {
//            return 0;
//        }

        return 1;
    }

    /**
     * 批量删除商品图片
     *
     * @param ids 需要删除的商品图片主键
     * @return 结果
     */
    @Override
    public int deleteImageByIds(Long[] ids) {
        String idsStr = Arrays.stream(ids)
                .map(Object::toString)
                .collect(Collectors.joining(","));
        List<Long> basicIdList = imageMapper.selectBasicIdListByIds(idsStr);
        String basicIds = basicIdList.stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
        imageMapper.batchUpdateStatus(idsStr, 2, "");
        return productMapper.batchUpdateStatus(basicIds, 2, "");
    }

    @Override
    public int batchAccessByIds(Long[] ids, String optName) {
        String idsStr = Arrays.stream(ids)
                .map(Object::toString)
                .collect(Collectors.joining(","));
        List<Long> basicIdList = imageMapper.selectBasicIdListByIds(idsStr);
        String basicIds = basicIdList.stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
        imageMapper.batchUpdateStatus(idsStr, 1, optName);
        int row = productMapper.batchUpdateStatus(basicIds, 1, optName);
        return row;
    }

    @Override
    public int batchOffLineByIds(Long[] ids, String optName, Integer status) {
        String idsStr = Arrays.stream(ids)
                .map(Object::toString)
                .collect(Collectors.joining(","));
        List<Long> basicIdList = imageMapper.selectBasicIdListByIds(idsStr);
        String basicIds = basicIdList.stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
        imageMapper.batchUpdateStatus(idsStr, status, optName);
        int row = productMapper.batchUpdateStatus(basicIds, status, optName);
        return row;
    }


    /**
     * 删除商品图片信息
     *
     * @param id 商品图片主键
     * @return 结果
     */
    @Override
    public int deleteImageById(Long id) {
        return imageMapper.deleteImageById(id);
    }

    @Override
    public Image getImageBySku(String sku) {
        return imageMapper.getImageBySku(sku);
    }
}
